<template>
	<div>
		<web-view height="100%" :src="src" @message="message" :webview-styles="webviewStyles"></web-view>
	</div>
</template>
<script>
import { getAddressCode } from "@/api/address";
import config from '@/config/config';
import permision from "@/js_sdk/wa-permission/permission.js";
export default {
  data() {
    return {
      config,
	  zoom:12,
	  baseSrc:'',
	  src:'http://192.168.110.201:10002/tdt/tdt.html',
	  lat:'',
	  lon:'',
	   webviewStyles: {  
					  progress: {  
						  color: '#f0b90b'  
					  }  
				  },  
	   wv: null, 
	   timer:null,
	   that:null
    };
  },
  mounted() {
    this.init();
	
	
  },
  onUnload() {
  	 console.log('onUnload');
	if(this.timer !=null){
		clearInterval(this.timer);
		this.timer = null;
	}
  },
  onLoad() {  
        this.that = this;  
		
	   
     },
    methods: {
	// 初始化地图并且调用
	  initMap() {
		//定时2s发送位置
		let self=this;
		self.baseSrc=self.src;
		uni.getLocation({
			type: 'wgs84',
			success: function (res) {
				let data = encodeURIComponent(JSON.stringify('lon=' + res.longitude + '&lat=' + res.latitude));//hash值最好经过编码
				self.src = self.baseSrc+"#"+data;
				//console.log('self.src：' + self.src);
			}
		}); 
		
		 this.timer = setInterval(function() {
				uni.getLocation({
					type: 'wgs84',
					success: function (res) {
						let data = encodeURIComponent(JSON.stringify('lon=' + res.longitude + '&lat=' + res.latitude));//hash值最好经过编码
						self.src = self.baseSrc+"#"+data;
						console.log('self.src：' + self.src);
					}
				}); 
		 	}, 3000);
		
		// uni.chooseLocation({
		//   success: function (res) {
		//     /**获取地址详情地址 */
		//     that.posToCity(res.latitude, res.longitude).then((val) => {
		//       /**获取地址code */
		//       getAddressCode(
		//         val.regeocode.addressComponent.citycode,
		//         val.regeocode.addressComponent.township
		//       ).then((code) => {
		//         that.$emit("callback", { ...val, ...res, ...code });
		//         that.$emit("close");
		//       });
		//     });
		//   },
		//   fail(e) {
		//     console.log(e)
		//     that.$emit("close");
		//   },
		// });
	  },
	message(event){//获取h5页面返回的数据
		let res = event.detail.data
		// this.lon = res.lon
		// this.lat = res.lat
		// const eventChannel = this.getOpenerEventChannel();
		// eventChannel.emit("locationMsg",{data:res});//传递上一页面的数据
		// console.log(event.detail.data);
		// uni.navigateBack()
	    console.log('收到来自web-view的消息：', JSON.stringify(res))
		//console.log("event.detail.data="+JSON.stringify(res))
		
		/**获取地址详情地址 */
		// this.that.posToCity(res.latitude, res.longitude).then((val) => {
		//   /**获取地址code */
		//   getAddressCode(
		//     val.regeocode.addressComponent.citycode,
		//     val.regeocode.addressComponent.township
		//   ).then((code) => {
		//    console.log("code="+JSON.stringify(code))
		//   });
		// });
	},
	// 打开地图并访问权限
	async clickUniMap() {
	  // #ifdef APP-PLUS
	  let that = this;
	  if (plus.os.name == "iOS") {
	    // ios系统
	   var result = permision.judgeIosPermission("location");
		if (result) {
		 that.initMap();
		} else {
		  that.refuseMap();
		}
	  } else {
	    // 安卓
		var result =await permision.requestAndroidPermission("android.permission.ACCESS_FINE_LOCATION");
		if (result == 1) {
		 that.initMap();
		} else {
		  that.refuseMap();
		}
	  }
	  // #endif
	},
	
	// 如果拒绝权限 提示区设置
	refuseMap() {
	  uni.showModal({
	    title: "温馨提示",
	    content: "您已拒绝定位,请开启",
	    confirmText: "去设置",
	    success(res) {
	      if (res.confirm) {
	        //打开授权设置
	        // #ifndef MP-WEIXIN
	        uni.getSystemInfo({
	          success(res) {
	            if (res.platform == "ios") {
	              //IOS
	              plus.runtime.openURL("app-settings://");
	            } else if (res.platform == "android") {
	              //安卓
	              let main = plus.android.runtimeMainActivity();
	              let Intent = plus.android.importClass(
	                "android.content.Intent"
	              );
	              let mIntent = new Intent("android.settings.ACTION_SETTINGS");
	              main.startActivity(mIntent);
	            }
	          },
	        });
	        // #endif
	      }
	    },
	  });
	},
	
	// 获取安卓是否拥有地址权限
	async requestAndroidPermission(permisionID) {
	  
	},
   

    // 根据当前客户端判断展示不同类型数据
    init() {
      // #ifdef MP-WEIXIN
      this.wechatMap();
      // #endif
      // #ifndef MP-WEIXIN
      this.clickUniMap();
      // #endif
    },

    // 如果是微信小程序单独走微信小程序授权模式
    wechatMap() {
      let that = this;
      uni.authorize({
        scope: "scope.userLocation",
        success() {
          // 允许授权
          that.initMap();
        },
        fail() {
          //拒绝授权
          uni.showModal({
            content: "检测到您没打开获取地址功能权限，是否去设置打开？",
            confirmText: "确认",
            cancelText: "取消",
            success: (res) => {
              if (res.confirm) {
                // 打开设置好后重新刷新地图
                uni.openSetting({
                  success: (res) => {
                    that.initMap();
                  },
                });
              } else {
                return false;
              }
            },
          });
          return false;
        },
      });
    },
	
    // 获取城市的数据
    posToCity(latitude, longitude) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `https://restapi.amap.com/v3/geocode/regeo`,
          method: "GET",
          data: {
            key: config.aMapKey, //web服务的key
            location: `${longitude},${latitude}`,
          },
          success: ({ data }) => {
            const { status, info } = data;
            if (status === "1") {
              resolve(data);
            } else {
              reject(info);
            }
          },
          fail: (err) => {
            reject(err);
          },
        });
      });
    },
  },
};
</script>
<style lang="scss" scoped>
</style>